package cn.yuanqiao.web.controller.cqbc;

import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.cqbc.common.mapper.MapperToolsMapper;
import cn.yuanqiao.cqbc.dataManage.domain.DataManage;
import cn.yuanqiao.cqbc.dataManage.service.IDataManageService;
import cn.yuanqiao.cqbc.util.FileDownload;
import cn.yuanqiao.cqbc.yqCarrierManage.domain.YqCarrierManage;
import cn.yuanqiao.cqbc.yqCarrierManage.service.YqCarrierManageService;
import cn.yuanqiao.cqbc.yqSetPlate.domain.YqSetPlateRule;
import cn.yuanqiao.cqbc.yqSetPlate.exception.SetPlateRuleException;
import cn.yuanqiao.cqbc.yqSetPlate.service.YqSetPlateRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 组盘规则表控制器
 *
 * @author lyk
 * @Date 2022-11-22 16:30:40
 */
@RestController
@RequestMapping("/cqbc/yqSetPlateRule")
public class YqSetPlateRuleController extends BaseController {

    @Autowired
    private YqSetPlateRuleService yqSetPlateRuleService;

    @Autowired
    private IDataManageService dataManageService;

    @Resource
    private MapperToolsMapper DbTool;

    @Autowired
    private YqCarrierManageService yqCarrierManageService;
    /*@Autowired
    private YqDataManageService yqDataManageService;

    @Autowired
    private FileQueryService fileQueryService;

    @Autowired
    private EepPackageService eepPackageService;

    @Autowired
    private YqCarrierManageService yqCarrierManageService;

    @Autowired
    private YqCarrierHddaService yqCarrierHddaService;
    @Autowired
    private HddaService hddaService;
    @Resource
    private DictMapper sysDictDao;

    @Resource
    MapperToolsMapper DbTool;*/


    /**
     * 新增接口
     *
     * @author lyk
     * @Date 2022-11-22
     */
    @Log(title = "新增组盘规则", businessType = BusinessType.INSERT)
    @PostMapping("/addItem")
    public AjaxResult addItem(@RequestBody YqSetPlateRule YqSetPlateRule) {
        return toAjax(yqSetPlateRuleService.add(YqSetPlateRule));
    }

    /**
     * 编辑接口
     *
     * @author lyk
     * @Date 2022-11-22
     */
    @Log(title = "编辑组盘规则", businessType = BusinessType.UPDATE)
    @PutMapping("/editItem")
    public AjaxResult editItem(@RequestBody YqSetPlateRule YqSetPlateRule) {
        return toAjax(yqSetPlateRuleService.update(YqSetPlateRule));
        //return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author lyk
     * @Date 2022-11-22
     */
    @Log(title = "删除组盘规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("id") Long id) {
        return toAjax(yqSetPlateRuleService.delete(id));
        //return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author lyk
     * @Date 2022-11-22
     */
    @GetMapping(value = "/{ID}")
    @Log(title = "组盘规则详情", businessType = BusinessType.SELECT)
    public AjaxResult detail(@PathVariable("ID") Long ID) {
        YqSetPlateRule detail = yqSetPlateRuleService.getById(ID);
        return success(detail);
        //YqSetPlateRule detail = this.yqSetPlateRuleService.getById(YqSetPlateRule.getId());
        //return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author lyk
     * @Date 2022-11-22
     */

    @Log(title = "组盘规则列表查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(YqSetPlateRule YqSetPlateRule) {
        //return this.yqSetPlateRuleService.findPageBySpec(YqSetPlateRule);
        List<YqSetPlateRule> list = yqSetPlateRuleService.findPageBySpec(YqSetPlateRule);
        return getDataTable(list);
    }

    /**
     * 查看详情接口
     *
     * @author lyk
     * @Date 2022-11-22
     */
    /*@RequestMapping("/getAddData")
    public ResponseData getAddData(YqSetPlateRule YqSetPlateRule) {
        Map<String, Object> addData = this.yqSetPlateRuleService.getAddData(YqSetPlateRule);
        return ResponseData.success(addData);
    }*/

    /**
     * 查看详情接口
     * ！important  size 的单位是Byte 前端乘以两个1024在往后端传
     * @author lyk
     * @Date 2022-11-22
     */
    @PostMapping("/setPlantDetail")
    public AjaxResult setPlantDetail(@RequestBody List<YqSetPlateRule> list, String size, String count) {
        //拿到规则明细
        count = String.valueOf(Integer.parseInt(count)*1024);
        List<DataManage> yqDataManageList = new ArrayList<>();
        String tenantCode = SecurityUtils.getTenantCode();
        for (YqSetPlateRule item :list) {
            //通过规则查询到对应的档案数据包
            List<String> yqDataManages = yqSetPlateRuleService.findBySetPlant(item);
            Set<String> set = new TreeSet<String>();
            yqDataManages.forEach(dataItem -> {
                set.add(String.valueOf(dataItem));
            });

            //TODO 等待拿到档案详细信息去组盘
            set.forEach(dataId->{
                DataManage byId = dataManageService.getDataManagebyId(Long.valueOf(dataId));
                String name=DbTool.getSingleVal("select name from "+tenantCode+"_CATEGORY where id= "+byId.getCategory());

                byId.setCategoryName(name);
                //List<Archives> withId = fileQueryService.getWithDataIdNoSetPlate(String.valueOf(yqDataManages.get(i)));
                yqDataManageList.add(byId);
            });
            /*for(int i=0;i<set.size();i++){
                YqDataManage byId = yqDataManageService.getById(set.g(i));
                //List<Archives> withId = fileQueryService.getWithDataIdNoSetPlate(String.valueOf(yqDataManages.get(i)));
                yqDataManageList.add(byId);
            }*/
        }
        List<List<DataManage>> result = null;
        try {
            result = yqSetPlateRuleService.getPageDateZip(yqDataManageList,size,count);
        } catch (SetPlateRuleException e) {
            e.printStackTrace();
            //return ResponseData.error(e.getMessage());
            return error(e.getMessage());
        }
        return success(result);
    }

    /*@RequestMapping("/downLoadZipFile")
    public ResponseData downLoadZipFile(@RequestBody List<YqSetPlateRule> list, String size, String count) {
        //拿到规则明细
        List<Archives> yqDataManageList = new ArrayList<>();
        //List<YqDataManage> yqDataManageList = new ArrayList<>();
        for (YqSetPlateRule item :list) {
            //通过规则查询到对应的档案数据包
            List<String> yqDataManages = yqDataManageService.findBySetPlant(item);

            Set<String> set = new TreeSet<String>();
            yqDataManages.forEach(dataItem -> {
                set.add(String.valueOf(dataItem));
            });

            //TODO 等待拿到档案详细信息去组盘
            for(int i=0;i<set.size();i++){
                List<Archives> withId = fileQueryService.getWithDataIdNoSetPlate(String.valueOf(yqDataManages.get(i)));
                yqDataManageList.addAll(withId);
            }
        }

        System.out.println(111);
        List<List<Archives>> result = null;
        try {
            result = yqSetPlateRuleService.getPageDate(yqDataManageList,size,count);
        } catch (SetPlateRuleException e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        }
        //Map<String, Object> addData = this.yqSetPlateRuleService.getAddData(YqSetPlateRule);
        return ResponseData.success(result);
    }
*/
    @RequestMapping("/download")
    public void download(@RequestHeader String name, @RequestHeader String path, @RequestHeader String format, HttpServletResponse response) {
        try {
            String filePath = path+ File.separator+name+"."+format;
            FileDownload.fileDownload(response,filePath,name+"."+format);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 列表的件或卷打包
     *
     *
     */
    @PostMapping("/listPackage")
    public void listPackageEep(@RequestBody List<Map<String,String>> dataList, @RequestHeader boolean webdownload, @RequestHeader(required = false) String carrierId, HttpServletResponse response) {
        try {
/*
            String type=DbTool.getSingleVal("select type from YQ_HDDACATEGORY where id= "+dataList.get(0).get("category"));
*/
            /*Map<String, Object> map = new HashMap<>();
            String ids = "";
            for (Map<String, String> item : dataList) {
                ids += item.get("daId");
                ids += ",";
            }
            ids = ids.substring(0,ids.length()-1);
            if("v".equalsIgnoreCase(type)) {
                List<Map<String, Object>> singleListBySql = DbTool.getListResult("select folder_id as FOLDER_ID from YQ_DA_FOLDER where da_id in(" + ids + ")  GROUP BY folder_id ");
                for (Map<String, Object> item : singleListBySql) {
                    ids = "";
                    ids += item.get("FOLDER_ID") + ",";
                }
                ids = ids.substring(0,ids.length()-1);
            }

            String userName = LoginContextHolder.getContext().getUser().getName();
            String userId = String.valueOf(LoginContextHolder.getContext().getUser().getId());
            map.put("ids",ids);
            map.put("userid",userId);
            map.put("username",userName);
            map.put("categoryId",dataList.get(0).get("categoryId"));
            map.put("dataList",dataList);*/
            //Map<String, Object> result = eepPackageService.listPackageEep(map);
            //String filePath = dataList.get(0).toString();
            List<String> filesPath = new ArrayList<>();
            dataList.forEach(item->{
                filesPath.add(item.get("path")+File.separator+item.get("name")+"."+item.get("format"));
            });
            //String filePath = pack(filesPath);
            if (webdownload) {
                String filePath = pack(filesPath);
                int index = filePath.lastIndexOf("/");
                if (index==-1){
                    index = filePath.lastIndexOf("\\");
                }
                FileDownload.fileDownload(response, filePath.substring(0,index), filePath.substring(index+1));
            }else {
                //YqCarrierManage YqCarrierManage = new YqCarrierManage();
                //YqCarrierManage.setId(Long.valueOf(carrierId));
                if(StringUtils.isNotEmpty(carrierId) && !"null".equals(carrierId)){
                    YqCarrierManage bySpec = yqCarrierManageService.getById(Long.valueOf(carrierId));
                    for (String filePathItem :filesPath) {
                        //copy
                        yqSetPlateRuleService.copyFileToPath(filePathItem,bySpec.getSavePath());
                        //  yqSetPlateRuleService.moveFileToPath(filePathItem,bySpec.getSavePath());
                    }
                }
                String tenantCode = SecurityUtils.getTenantCode();
                //更改是否已组盘字段
                for (Map<String, String> item:dataList){
                    String id = item.get("id");
                    DbTool.executeUpdate("update "+tenantCode+"_CQBC_HDDA set IS_ZUPAN = '1' where data_id = "+id);
                }
                //下载到指定载体给给档案添加载体id标识(转以后不可以再下载)
                /*for (Map<String, String> item:dataList){
                    hddaService.update(item.get("daId"),carrierId);
                }
                for (Map<String, String> item :dataList) {
                    YqCarrierHddaParam yqCarrierHddaParam = new YqCarrierHddaParam();
                    yqCarrierHddaParam.setDaId(item.get("daId"));
                    yqCarrierHddaParam.setCarrCode(bySpec.getName());
                    yqCarrierHddaParam.setCarrId(bySpec.getId());
                    yqCarrierHddaService.add(yqCarrierHddaParam);
                }*/
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.setStatus(200);
       // return null;
    }

    /**
     * 将指定路径下的所有文件打包成一个zip包，并返回zip包的路径。
     * @param files 要打包的文件路径列表
     * @return 生成的zip包的路径
     * @throws IOException
     */
    public static String pack(List<String> files) throws IOException {
        // 创建一个临时文件，并设置文件名为随机生成的UUID
        File zipFile = File.createTempFile("temp", ".zip");
        String zipFilePath = zipFile.getAbsolutePath();

        // 创建ZipOutputStream对象用来写入压缩文件
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

        // 遍历文件列表，依次加入zip包中
        for (String filePath : files) {
            File file = new File(filePath);
            FileInputStream in = new FileInputStream(file);

            // 添加ZipEntry，并将输入流写入到ZipOutputStream中
            out.putNextEntry(new ZipEntry(file.getName()));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            in.close();
        }

        // 关闭ZipOutputStream对象
        out.close();

        // 返回压缩文件的全路径
        return zipFilePath;
    }


    /**
     * 获取部门的tree列表，ztree格式
     *
     * @author fengshuonan
     * @Date 2019-8-27 15:24
     */
    @PostMapping(value = "/tree")
    public AjaxResult tree() {
        List<TreeSelect> list = yqSetPlateRuleService.tree();
        //List<ZTreeNode> tree = this.yqSetPlateRuleService.carrierTreeList();
        //tree.add(ZTreeNode.createParent1());
        return success(list);
    }
}


